import React, { useRef, useState } from 'react';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, message, Modal } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import type { RightsListItem } from './data';
import { queryRights, addRights, deleteRights } from './service';

const Rights: React.FC = () => {
  const actionRef = useRef<ActionType>();
  /**
   * 新增用户信息
   */
  const [addModalVisible, setAddModalVisible] = useState(false);
  const handleAdd = async (fields: RightsListItem) => {
    const hide = message.loading('正在添加');
    try {
      await addRights({ ...fields });
      hide();
      message.success('添加成功');
      return true;
    } catch (err) {
      hide();
      message.error('添加失败请重试');
      return false;
    }
  };

  /**
   * 删除用户信息
   */
  const handleDelete = async (fields: RightsListItem) => {
    Modal.confirm({
      title: '提醒',
      icon: <ExclamationCircleOutlined />,
      content: '确认删除该员工吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const hide = message.loading('正在删除');
        try {
          const success = await deleteRights({ id: fields.id });
          hide();
          message.success('删除成功');
          if (success && actionRef.current) {
            actionRef.current.reload();
          }
          return true;
        } catch (err) {
          hide();
          message.error('删除失败请重试');
          return false;
        }
      },
    });
  };

  /**
   * 列表字段配置
   */
  const columns: ProColumns<RightsListItem>[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '用户姓名',
      dataIndex: 'name',
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
    },
    {
      title: '权限',
      dataIndex: 'rights',
      valueEnum: {
        admin: {
          text: 'admin',
          status: '',
        },
        管理员: {
          text: '管理员',
          status: '',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, item) => [
        <a
          key="delete"
          onClick={() => {
            handleDelete(item);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<RightsListItem>
        headerTitle="用户管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="add"
            onClick={() => {
              setAddModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增
          </Button>,
        ]}
        columns={columns}
        request={(params, sorter, filter) => queryRights({ ...params, sorter, filter })}
        pagination={{
          pageSize: 10,
        }}
      />
      <ModalForm
        title="新增用户"
        width="300px"
        visible={addModalVisible}
        onVisibleChange={setAddModalVisible}
        onFinish={async (value) => {
          // 确认提交操作
          const success = await handleAdd(value as RightsListItem);
          if (success) {
            setAddModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '用户姓名为必填项',
            },
          ]}
          width="sm"
          name="name"
          label="用户姓名"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '手机号码为必填项',
            },
          ]}
          width="sm"
          name="phone"
          label="手机号码"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '权限为必选项',
            },
          ]}
          width="sm"
          name="rights"
          label="权限"
          valueEnum={{
            admin: {
              text: 'admin',
              status: '',
            },
            管理员: {
              text: '管理员',
              status: '',
            },
          }}
        />
      </ModalForm>
    </PageContainer>
  );
};

export default Rights;
